import { fileURLToPath, URL } from 'node:url';

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import path from "path";

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';
import monacoEditorPlugin from 'vite-plugin-monaco-editor'

// import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig(( {command , mode} ) => {
    const config = loadEnv(mode, './')
    return {
        plugins: [
            vue(),
            createSvgIconsPlugin({
                // 需要自动导入的 svg 文件目录（可自行修改）我的路径如下图所示
                iconDirs: [path.resolve(process.cwd(), "src/components/svgIcon/svg")],
                // 执行icon name的格式（可自行修改）
                symbolId: "icon-[dir]-[name]",
            }),
            AutoImport({ //按需引入前置条件
              resolvers: [ElementPlusResolver()],
            }),
            Components({ //按需引入前置条件
              resolvers: [ElementPlusResolver()],
            }),
            monacoEditorPlugin.default({
              languageWorkers: ['editorWorkerService', 'typescript', 'json', 'html']
            }),
            //依赖包体积视图
          //   visualizer({
          //     filename: 'dist/stats.html',
          //     open: true,
          //     gzipSize: true,
          //     brotliSize: true,
          //     template: 'treemap'
          // })
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            }
        },
        // 添加 assetsInclude 配置，将 .xlsx 文件视为静态资源
        assetsInclude: ['**/*.xlsx'],
        base: config.VITE_BASEURL,
        // 添加 define 配置，定义编译时特性标志
        define: {
            __VUE_OPTIONS_API__: true,
            __VUE_PROD_DEVTOOLS__: false,
            __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false
        },
        server: {
            cors: true,
            host: 'localhost',
            open: true,
            port: 8080,
            proxy: {
                '/test': {
                    // target: 'http://192.168.1.158:80',
                    
                    target: 'https://demo.cwboan.com',
                    secure: false,
                    protocolRewrite: 'https',

                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/test/, '')
                },
            }
        },
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: '@import"@/assets/css/main.scss";'
                },
                less: {
                    // // 覆盖 iView 的默认主题色
                    // modifyVars: {
                    //   '@primary-color': '#8c0776',  // 设置你想要的主题颜色
                    // },
                    javascriptEnabled: true, // 允许使用 JavaScript 语法
                  },
              },
              postcss: {
                plugins: [
                  {
                    postcssPlugin: 'internal:charset-removal',
                    AtRule: {
                      charset: (atRule) => {
                        if(atRule.name ==='charset'){
                          atRule.remove()
                        }
                      }
                    },
                  },
                  tailwindcss,
                  autoprefixer,
                ]
             }
        },
        build: {
            minify: true,
            assetsDir: 'static',
            outDir: 'dist',
            sourcemap: false,
            chunkSizeWarningLimit: 1500,
            rollupOptions: {
                output: {
                    // 最小化拆分包
                    manualChunks(id) {
                        if (id.includes("node_modules")) {
                            return id.toString().split("node_modules/")[1].split("/")[0].toString()
                        }
                    },
                    // 用于从入口点创建的块的打包输出格式[name]表示文件名,[hash]表示该文件内容hash值
                    entryFileNames: 'static/js/[name].[hash].js',
                    // 用于命名代码拆分时创建的共享块的输出命名
                    // 　　chunkFileNames: 'js/[name].[hash].js',
                    // 用于输出静态资源的命名，[ext]表示文件扩展名
                    assetFileNames: 'static/[ext]/[name].[hash].[ext]',
                    // 拆分js到模块文件夹
                    chunkFileNames: (chunkInfo) => {
                        const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : [];
                        const fileName = facadeModuleId[facadeModuleId.length - 2] || '[name]';
                        return `static/js/${fileName}/[name].[hash].js`;
                    },
                }
            }
        }
    }
})
